// MIT License (MIT)
// 
// Copyright (c) 2014 K Ercan Turkarslan
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using CodeGen;
using CollectionsLibrary;

namespace MiosGenerator
{
    public class Action : MiosCollectionItem
    {
        public String ActionName { get { return Name; } }

        #region Property Arguments : ItemsCollection;
        private readonly ItemsCollection<ActionArgument> _arguments;

        public ActionArgument[] Arguments { get { return _arguments.Items;  } }
        #endregion

        #region ReadOnly Property OutArguments : List<ActionArgument>;
        private List<ActionArgument> _outArguments;

        public List<ActionArgument> OutArguments
        {
            get
            {
                return _outArguments ??
                       (_outArguments = _arguments.Items.Where(argument => argument.IsOutParameter).ToList());
            }
        }
        #endregion

        #region ReadOnly Property InArguments : List<ActionArgument>;
        private List<ActionArgument> _inArguments;

        public List<ActionArgument> InArguments
        {
            get
            {
                return _inArguments ??
                       (_inArguments = _arguments.Items.Where(argument => !argument.IsOutParameter).ToList());
            }
        }
        #endregion

        #region FirstArgument : ActionArgument
        public ActionArgument FirstArgument
        {
            get { return _arguments.FirstItem(); }
        }
        #endregion

        #region IsGetAction method
        public Boolean IsGetAction()
        {
            return ActionName.StartsWith("Get") && 
                   (_arguments.Count() == 1) &&
                   FirstArgument.IsOutParameter && 
                   (FirstArgument.RelatedStateVariable != null);
        }
        #endregion

        #region IsSetAction method
        public Boolean IsSetAction()
        {
            return ActionName.StartsWith("Set") && 
                   (_arguments.Count() == 1) &&
                   !FirstArgument.IsOutParameter && 
                   (FirstArgument.RelatedStateVariable != null);
        }
        #endregion

        #region GetSignature method
        internal String GetSignature()
        {
            var actionSignature = new StringBuilder(String.Format("{0}(", ActionName));

            var firstArg = true;
            foreach (var argument in _arguments.Items)
            {
                actionSignature.AppendFormat("{0}{1} {2}",
                                    firstArg ? "" : ", ",
                                    argument.DataType.Upnp,
                                    argument.Name);

                firstArg = false;
            }
            actionSignature.Append(")");

            return actionSignature.ToString();
        }

        #endregion

        #region Generate Method

        #region GetMethodName method
        private static String GetMethodName(String actionName, ItemsCollection<StateVariable> stateVariables)
        {
            var errorMessage = new StringBuilder();

            if (actionName.Contains("/"))
            {
                errorMessage.Append("[Action ActionName contains '/'!]");
            }

            while (actionName.Contains("/"))
                actionName = actionName.Replace('/', '_');

            if (!Char.IsLetter(actionName[0]))
            {
                errorMessage.Append("[Action ActionName does not start with a letter!]");
                actionName = actionName.Insert(0, "Action_");
            }

            if (stateVariables.GetByName(actionName) != null)
            {
                errorMessage.Append("[Action ActionName collides with ActionName of a State Variable!]");
                actionName = actionName.Insert(0, "Action_");
            }

            if (actionName == "Finalize")
            {
                errorMessage.Append("[Action ActionName collides with a C# reserved word!]");
                actionName = actionName.Insert(0, "Action_");
            }

            return errorMessage.Length > 0 ? String.Format("/* WARNING: {0} */ {1}", errorMessage, actionName) : actionName;
        }
        #endregion

        internal void Generate(CodeBlock cb, ItemsCollection<StateVariable> stateVariables)
        {
            // Generates a Mios Action method with or without parameters 
            // e.g.: ToggleState() of HaDevice1
            // e.g. : S_HomeAutomationGateway1.xml - GetUserData(String dataFormat, UInt32? dataVersion) : String;
            // e.g.: S_HaDevice1.xml - SetPollFrequency(Boolean pollingEnabled, Byte pollMinDelay)
            //

            if (!FromDescription)
            {
                cb.Comment(
                    "WARNING: This action was not defined in the service file.",
                    "However it was referenced in Actions Luup request or USER_DATA."
                    );
            }

            var methodName = GetMethodName(ActionName, stateVariables);

            var isFunction  = (OutArguments.Count == 1);
            var isProcedure = !isFunction;

            var hasArguments = (_arguments.Count() != 0);

            var csParams = new StringBuilder();

            if (hasArguments)
            {
                var firstArg = true;
                foreach (var argument in _arguments.Items)
                {
                    csParams.Append(String.Format("{0}{1}{2} {3}",
                        firstArg ? "" : ", ",
                        (argument.IsOutParameter && isProcedure) ? "out " : "",
                        argument.Optional ? argument.DataType.Nullable : argument.DataType.CSharp,
                        argument.CamelCaseName));

                    firstArg = false;
                }
            }

            cb.Action_Begin(methodName, csParams.ToString(), isFunction ? OutArguments.First().DataType.CSharp : null);

            if (hasArguments)
            {
                foreach (var argument in from ActionArgument argument in InArguments
                    where (argument.DataType.IsString && !argument.Optional)
                    select argument)
                {
                    cb.CheckNullOrEmptyStringParameter(argument.CamelCaseName);
                }

                if (OutArguments.Any())
                {
                    cb.Comment(
                        "WARNING: This version of code generator does not know how to generate Http Luup requests with out variables.",
                        "Below generated code may not function properly!",
                        "");

                    if (isFunction)
                    {
                        cb.Insert(String.Format("return FromLuup{0}(", OutArguments.First().DataType.CSharp));
                    }
                    else
                    {
                        // Set default value for each out argument.
                        //
                        foreach (var argument in OutArguments)
                        {
                            cb.Insert(
                                String.Format("{0} = default({1});",
                                    argument.CamelCaseName,
                                    argument.Optional ? argument.DataType.Nullable : argument.DataType.CSharp));
                        }
                        cb.NewLine();
                    }
                }
            }

            if (hasArguments)
            {
                cb.Insert(String.Format("Engine.Luup_CallAction(base.DeviceId, base.ServiceId, \"{0}\"", ActionName));

                foreach (var argument in _arguments.Items)
                {
                    if (isFunction && argument.IsOutParameter)
                        continue;

                    var argumentParam = new StringBuilder(", ");

                    if (argument.Optional)
                    {
                        argumentParam.AppendFormat("{0} == null ? \"\" : ", argument.CamelCaseName);
                    }

                    argumentParam.AppendFormat("String.Format(\"{0}={{0}}\", ToLuup({1}))",
                        argument.Name,
                        argument.CamelCaseName);

                    cb.InsertIndented(argumentParam.ToString());
                }

                cb.InsertIndented(isFunction ? ")); // Engine.Luup_CallAction" : "); // Engine.Luup_CallAction");
            }
            else
            {
                cb.Insert(String.Format("Engine.Luup_CallAction(base.DeviceId, base.ServiceId, \"{0}\");", ActionName));                
            }

            cb.Action_End(methodName);
        }

        #endregion

        #region Constructor(s)

        internal Action(XNode xNode, ItemsCollection<StateVariable> stateVariables)
            : base(xNode.GetValue("name"))
        {
            _arguments = new ItemsCollection<ActionArgument>();

            if (!xNode.GetChildren("argumentList").Any())
                return;

            foreach (var childNode in xNode.GetChildren("argumentList"))
            {
                _arguments.Add(new ActionArgument(childNode, stateVariables), false);
            }
        }

        internal Action(String name, ItemsCollection<ActionArgument> arguments)
            : base(name)
        {
            FromDescription = false; 

            _arguments = arguments;
        }

        #endregion
    }
}